﻿using EasyCore.Caching.Interfaces;
using EasyCore.Caching.Memory;
using EasyCore.Caching.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EasyCore.App;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SimpleRedis;
using Microsoft.AspNetCore.Builder;
using EasyCore.Caching.Consts;
using EasyCore.Caching.Options;

namespace EasyCore.Caching
{
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 增加缓存
        /// </summary>
        public static IServiceCollection AddEasyCache(this IServiceCollection services)
        {
            var config = EasyApp.Configuration;
            var cacheOptions = config.GetSection("CacheSettings").Get<CacheSettingsOptions>();
            services.AddSingleton(cacheOptions);

            //如果有redis连接字符串
            if (cacheOptions != null && cacheOptions.UseRedis)
            {
                var connectionString = $"server={cacheOptions.RedisSettings.Address};password={cacheOptions.RedisSettings.Password};db={cacheOptions.RedisSettings.Db}";
                services.AddSimpleRedis(connectionString);        //注入redis
                services.AddSingleton<IEasyCacheService, RedisCacheService>(); //注入redis服务类
            }
            else
            {
                services.AddSingleton<IEasyCacheService, MemoryCacheService>(); //注入内存缓存服务类
            }
            return services;
        }

        /// <summary>
        /// 使用缓存
        /// </summary>
        public static WebApplication UseEasyCache(this WebApplication app)
        {
            var cacheOptions=  app.Services.GetRequiredService<CacheSettingsOptions>();//获得配置属性
            //如果需要清除缓存
            if (cacheOptions.UseRedis && cacheOptions.RedisSettings.ClearRedis)
            {
                var redis = app.Services.GetRequiredService<IEasyCacheService>(); //获取redis服务                                                                  
                redis.DelByPattern(CacheConst.Cache_Prefix_Web); //删除redis的key
            }
            return app;
        }

    }
}
